package com.one.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.one.bean.User;
import com.one.constant.RedisPrefixConstant;
import com.one.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 监听所有db的过期事件__keyevent@*__:expired"
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {


    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 针对 redis 数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {


        // 获取到失效的 key，进行业务处理
        String expiredKey = message.toString();
       if (expiredKey.contains("RushTime")){
           List<Object> userRegistration = redisUtils.lGet("userRegistration", 0, -1);
//           List<Map> maps = JSON.parseArray(userRegistration.toString(), Map.class);
            userRegistration.forEach(map->{
                JSONObject jsonObject = JSON.parseObject(map.toString());
                redisUtils.set("活动提醒信息:"+jsonObject.getString("phone"),"抢购活动即将开始,请准备");
            });
           log.info("------ 监听redis失效队列,给活动登记用户发送提醒信息 ------");
       }

       if (expiredKey.contains(RedisPrefixConstant.TICKET_AUTO)){
           log.info("------监听失效键:{}------",expiredKey);
           // 获取下标
           String[] split = expiredKey.split(":");
           long index = Long.parseLong(split[split.length-1]);
           Object o = redisUtils.lGetIndex(split[0] +":"+ split[1], index);
           JSONObject jsonObject = JSON.parseObject(o.toString());
           jsonObject.put("status",0);
           List<Object> list = redisUtils.lGet(split[0] + ":" + split[1], 0, -1);
           List<JSONObject> couponList = list.stream().map(coupon -> JSON.parseObject(coupon.toString())).collect(Collectors.toList());
           couponList.get((int) index).put("status",0);
           redisUtils.lUpdateIndex(split[0] +":"+ split[1],index,couponList.get((int) index));
            log.info("*******优惠券已过期*******");
       }
    }
}